<template>
  <div class="m-form-item">
    <div class="m-form-item_title">
      <span class="title-required" v-if="required || rule.length > 0">* </span>
      <span>{{ label }}</span>
    </div>
    <div class="m-form-item_content">
        <slot ref="item"></slot>
    </div>
    <div v-if="showError && rule.length > 0" class="valid-error">
      {{ rule[0].message || '请完善' }}
    </div>
  </div>
</template>

<script>
import { reactive, toRefs } from 'vue'
import { isNotEmpty } from '/@/utils/utils'
export default {
    name: 'FormItem',
    props: {
        label: {
            type: String,
            default: '',
        },
        rule: {
            type: Array,
            default: () => {
                return []
            },
        },
        prop: {
            type: String,
            default: '',
        },
        model: {
            type: Object,
            default: () => {
                return {}
            },
        },
        required: {
            type: Boolean,
            default: false,
        },
    },
    setup(props) {
        const { rule, model, prop } = toRefs(props)
        const state = reactive({
            showError: false
        })
        const isError = () => {
            return state.showError
        }
        const validate = (call) => {
            if (rule.value.length > 0) {
                if (rule.value[0].type === 'array') {
                    state.showError = !(
                        Array.isArray(model.value[prop.value]) &&
                        model.value[prop.value].length > 0
                    )
                } else {
                    state.showError = !isNotEmpty(model.value[prop.value])
                }
            }
            if (!state.showError) {
            }
            if (call) {
                call(!state.showError)
            }
        }
        return {
            ...toRefs(state),
            validate,
            isError
        }
    }
}
</script>

<style scoped lang="scss">
.m-form-item {
  position: relative;
  padding: 10px 10px 20px 10px;
  background: white;
  //margin-top:5px;
  margin-bottom: 10px;

  & > div:first-child {
    margin-bottom: 8px;
    font-size: 1.2rem;
    color: #545456;
  }

  & > div:last-child {
    //padding: 0 5px;
  }

  .title-required {
    color: var(--el-color-danger);
  }

  .valid-error {
    color: var(--el-color-danger);
    position: absolute;
    font-size: 0.85rem;
  }
}
</style>